package ie.ucd.ABLE.MachineLearning;

import java.sql.*;
import java.util.Calendar;
import java.util.TimeZone;

//This class is used to build a connection to MySQL server.
public class MySQLConnect {

	private Connection dbConnection; 
	private String hostAddress; 
	private String userName; 
	private String userPassword; 
	private String dbName; 
	private int port = 3300;

	public MySQLConnect(String hostAddress, String userName, String userPassword, String dbName){

		this.hostAddress = hostAddress;
		this.userName = userName;
		this.userPassword = userPassword;
		this.dbName = dbName;
		dbConnection = mySQLConnect();
	}

	public Connection mySQLConnect(){

		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance( ); 
		} 
		catch (ClassNotFoundException e) {
			e.printStackTrace( ); 
		} 
		catch (InstantiationException e) {
			e.printStackTrace( ); 
		} 
		catch (IllegalAccessException e) {
			e.printStackTrace( );
		}
		try { 
			String url = "jdbc:mysql://" + hostAddress + ":" + port + "/" + dbName; 
			System.out.println("Connecting to " + url + " as " + userName); 
			return DriverManager.getConnection(url, userName, userPassword);
		} 
		catch (SQLException e) {
			System.out.println("Could not connect to MySQL server:");
			return null;
		}
	}

	public void updateTable(String query){

		try {
			Statement st = dbConnection.createStatement(); 
			st.executeUpdate(query); 
			st.close();
		} 
		catch (SQLException e) {
			System.out.println("Could not run query:");
			e.printStackTrace( ); 
		}
	}

	public ResultSet queryTable(String query){

		try {
			Statement st = dbConnection.createStatement(); 
			ResultSet rs = st.executeQuery(query); 
			return rs;
		} 
		catch (SQLException e) {
			System.out.println("Could not run query:");
			e.printStackTrace( ); 
			return null;
		}
	}

	public void closeConnection(){

		try {
			if(!dbConnection.isClosed()){
				dbConnection.close();
			}
			if (dbConnection.isClosed()) 
				System.out.println("Connection closed.");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public Connection getDbConnection() {
		return dbConnection;
	}

	public void setDbConnection(Connection dbConnection) {
		this.dbConnection = dbConnection;
	}

}
